<template>
  <div>
    <van-nav-bar
        title="整车写入申请详情"
        left-text="返回"
        left-arrow
        @click-left="routerBackMixin"
    />
    <div id="WritingApplicationDetail">

      <div class="WritingApplicationDetail-top">
        <div class="top-item rowSS">
          <h4>整车厂</h4>
          <h5>{{vehicleIniApplyData.assemblyPlant}}</h5>
        </div>
        <div class="top-item rowSS">
          <h4>单元控制类型</h4>
          <h5>{{vehicleIniApplyData.vehicleModel}}</h5>
        </div>
        <div class="top-item rowSS">
          <h4>VAN码</h4>
          <h5>{{vehicleIniApplyData.vanNumber}}</h5>
        </div>
        <div class="top-item rowSS">
          <h4>区域</h4>
          <h5>{{vehicleIniApplyData.area}}</h5>
        </div>
        <div class="top-item rowSS">
          <h4>申请人</h4>
          <h5>{{vehicleIniApplyData.applicantRealName}}</h5>
        </div>
        <div class="top-item rowSS">
          <h4>申请时间</h4>
          <h5>{{vehicleIniApplyData.ctime}}</h5>
        </div>
        <div class="top-item rowSS">
          <h4>备注</h4>
          <h5>{{vehicleIniApplyData.remark||'-'}}</h5>
        </div>
        <!--图片显示-->
        <div class="image-container">
          <h4 class="mt-2 mb-1 font-weight">技师图片</h4>
          <div class="rowSS flex-wrap">
            <van-image
                v-if="jsImageArr.length"
                @click.native="getLargeImg(index)"
                src="https://img01.yzcdn.cn/vant/cat.jpeg"
                v-for="(item,index) in zjImageArr" :key="index"
                :src="item.filePath" class="tp-container mr-1 mb-1"
            />
            <span class="mt-1 ml-1 mb-1">
              -
            </span>
          </div>
        </div>
      </div>
      <!--审批详情-->
      <div class="columnCC mt-2 mb-2">
        <h4 class="font-weight ">审批详情</h4>
      </div>
      <div class="rowSS mb-2">
        <h4 class="widthPx-150 font-weight">审批状态</h4>
        <div
            v-if="!isSHApprove"
            @click="showPicker=true"
            class="d-inline-block all-select-btn">
          <span class="widthPx-80">{{packingValue||'请选择'}}</span>
          <svg-icon  icon-class="btn-positon-icon"  class="ml-1" />
        </div>
        <div v-else class="d-inline-block all-select-btn">
          <span class="widthPx-80">{{packingValue}}</span>
        </div>
      </div>
      <!--勾选框-->
      <div v-for="(item,index) in vehicleIniApplyData.items" :key="index"
          class="rowSC mt-1">
        <van-checkbox shape="square"  class="widthPx-150"  v-model="item.checked">{{item.name}}</van-checkbox>
        <!--类型为2则是选择框-->
        <div  v-if="item.style==2" class="item-choose-item-container">
          <van-field
              readonly
              clickable
              class="widthPx-180"
              name="picker"
              :value="returnValue(item)"
              label=""
              placeholder="点击选择"
              @click="showPackingInput(item,index)"
          />
          <svg-icon  icon-class="btn-positon-icon"  class="item-choose-icon" />
        </div>
        <van-field  v-else class="widthPx-180"  v-model="item.writeValue" label="" />
      </div>
      <van-popup v-model="showPicker" position="bottom" :overlay="false">
        <van-picker
            value="已通过"
            title="选择"
            show-toolbar
            :columns="columns"
            :default-index="defaultChooseIndex"
            value-key="label"
            @confirm="onConfirm"
            @cancel="showPicker=false"
        />
      </van-popup>

      <!--拒绝原因 选择拒绝后显示-->
      <div class="border-bottom columnCS mt-1 mb" v-if="vehicleIniApplyData.audit===-1">
        <h4 class="widthPx-100 mb-1">拒绝原因</h4>
        <van-field class="widthPC-100" type="textarea"  v-model="vehicleIniApplyData.refuseReason" />
      </div>
      <!--添加图片-->
      <div class="mt-3" v-if="!isSHApprove">
        <h4 class="mb-1">专家添加图片：</h4>
        <van-uploader
            class="reset-upload-style"
            icon="plus" type="primary"
            :before-read="beforeRead"
            :max-count="5"
            v-model="imageFileList" multiple />
      </div>
      <!--图片显示-->
      <div class="image-container" v-else>
        <h4 class="mt-2 mb-1 font-weight">专家图片</h4>
        <div class="rowSS flex-wrap">
          <van-image
              v-if="zjImageArr.length"
              @click.native="getLargeImg(index)"
              src="https://img01.yzcdn.cn/vant/cat.jpeg"
              v-for="(item,index) in zjImageArr" :key="index"
              :src="item.filePath" class="tp-container mr-1 mb-1"
          />
          <span class="mt-1 ml-1 mb-2">
            -
          </span>
        </div>
      </div>
      <!--刷新次数-->
      <div class="rowSC inputItem">
        <h4 class="widthPx-100 ">刷写次数</h4>
        <van-stepper class="widthPx-100" v-if="!isSHApprove" v-model="vehicleIniApplyData.rewriteTimes"/>
        <div class="widthPx-80" v-else>{{vehicleIniApplyData.rewriteTimes||'-'}}</div>
      </div>
      <!--刷新次数-->
      <div class="rowSC inputItem" @click="chooseDateShow=true">
        <h4 class="widthPx-100 ">有效期</h4>
        <span class="widthPx-140 mr-1">{{vehicleIniApplyData.deadline||'请选择有效期'}}</span>
      </div>
      <van-popup v-model="chooseDateShow" position="bottom" :overlay="false">
        <van-datetime-picker
            v-model="vehicleIniApplyData.deadline"
            type="datetime"
            @cancel="chooseDateShow=false"
            @confirm="onChooseDateConfirm"
            title="选择完整时间"
            :min-date="minDate"
        />
      </van-popup>
      <!--确定提交按钮-->
      <van-button class="mt-4 mb-4" :disabled="isSHApprove"  style="background-color: #5169B1;color: #fff"  size="large"  @click="btnConfirm">确定</van-button>
    </div>
    <van-popup v-model="itemShowPicker" position="bottom">
      <van-picker
          show-toolbar
          :columns="itemColumns"
          value-key="content"
          @confirm="onConfirmItem"
          @cancel="itemShowPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
// import { mapState, mapMutations, mapActions } from 'vuex'
// import validMixins from '@/mixins/validMixins.js'
import { ImagePreview } from "vant"; // 引入Vant图片预览组件
export default {
  name: 'WritingApplicationDetail',
  components: {
    // TablesGZCJ,
  },
  // mixins: [validMixins],
  props: {
    // treeData: Array,
  },
  // mixins: [validMixins],
  data() {
    return {
      minDate: new Date(),
      packingValue: "",
      showPicker:false,
      checked:false,
      chooseDateShow:false,
      columns: [
        {value:0,label:"待审核"},
        {value:1,label:"已通过"},
        {value:-1,label:"拒绝"},
      ],
      columnsMap:{
        "0":"待审核",
        "1":"已通过",
        "-1":"拒绝",
      },
      defaultChooseIndex:"",
      imageFileList:[],
      vehicleIniApplyData:{},
      isSHApprove:false,
      /*请求*/
      showDatePicker:false,
      jsImageArr:[],
      zjImageArr:[],
      /*弹框选择器*/
      itemValue: '宁波',
      itemColumns: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
      itemShowPicker: false,
      currentChooseIndex:0
    }
  },
  computed: {
    // ...mapState('user', ['token', 'userInfo'])
  },
  watch: {
    // 'cmAddForm.enginePlatform': function(val) {
    //   console.log('enginePlatformval', val)
    //   if (val) {
    //     this.emissionOptionReq()
    //   }
    // }
  },
  created() {

  },
  mounted() {
    console.log(this.queryParamsMixin.params);
    this.getVehicleIniApplyReq();
  },

  methods: {
    returnValue(item){
      let itemContent=JSON.parse(item.content)
      let  findArrObjByKeyItem= this.$comentUtil.findArrObjByKey(itemContent,"value",item.writeValue);
      if(findArrObjByKeyItem){
        return  findArrObjByKeyItem.content
      }
    },
    showPackingInput(item,index){
      if(item.content){
        let itemContent=JSON.parse(item.content)
        this.itemShowPicker=item
        this.currentChooseIndex=index
        this.itemColumns=itemContent
        console.log("this.itemColumns", this.itemColumns);
        this.itemShowPicker=true
      }else{
        this.vantToastNoneMixin("该项没有选择项")
      }
    },
    onConfirmItem(itemValue){
      this.itemValue = itemValue.value;
      this.vehicleIniApplyData.items[this.currentChooseIndex].writeValue=itemValue.value
      this.itemShowPicker = false;
    },
    getLargeImg(index) {
      ImagePreview({
        images: this.vehicleIniApplyData.imgs.map((mItem)=>{
          return mItem.filePath
        }), // 预览图片的那个数组
        showIndex: true,
        loop: false,
        startPosition: index, // 指明预览第几张图
      })
    },
    onChooseDateConfirm(value){
      this.vehicleIniApplyData.deadline = this.$momentMini(value).format('YYYY-MM-DD HH:mm:ss')
      this.sleepMixin().then(()=>{
        this.chooseDateShow=false
      })
    },
    onConfirm(item){
      this.packingValue=item.label
      this.vehicleIniApplyData.audit=item.value
      this.showPicker=false
    },
    beforeRead(fileObj) {
      // 此时可以自行将文件上传至服务器
      console.log("file",fileObj);
      let formData=new FormData();
      formData.append('file',fileObj)
      this.$axiosReq({
        url: 'fileupload/upload',
        data:formData, method: 'POST', bfLoading: true,isUploadFile:true
      }).then(res => {
        this.imageFileList.push({
          name:res.data.name,
          url:res.data.url,
          filePath:res.data.url,
          type:2,
        })
        console.log(this.imageFileList);
        console.log("图片上传成功返回的地址", res);
      })
      return false
    },
    //确定按钮点击了
    btnConfirm(){
      this.auditVehicleIniApplySub();
    },

    //校验
    validSubData(){
      return new Promise((resolve,reject)=>{
        //刷写次数>1
        //判断审批状态是否修改了
        console.log("this.vehicleIniApplyData",this.vehicleIniApplyData.audit);
        if(this.vehicleIniApplyData.audit===0){
          this.vantToastNoneMixin("请先修改审核状态")
          reject();
        }
        //item输入
        for (let itemsKey of this.vehicleIniApplyData.items) {
          if((itemsKey.checked&&!itemsKey.writeValue)){
            this.vantToastNoneMixin(`【${itemsKey.name}】输入值为空`)
            reject();
          }
        }
        //拒绝原因
        if(this.vehicleIniApplyData.audit===-1&&!(this.vehicleIniApplyData.refuseReason)){
          this.vantToastNoneMixin("审核状态选择了拒绝，请填写拒绝原因")
          reject();
        }
        //有效期
        if(!this.vehicleIniApplyData.deadline){
          this.vantToastNoneMixin("有效期为空")
          reject();
        }
        resolve()
      })
    },
    /*数据请求*/
    getVehicleIniApplyReq() {
      const data = {
        id:this.queryParamsMixin.params.id
      }
      this.$axiosReq({
        url: 'vehicleIniApply/getVehicleIniApply',
        data,method: 'get', bfLoading: true,isParams:true,
      }).then(res => {
        if(res.data.items){
          res.data.items=res.data.items.map(fItem=>{
            fItem.checked=true
            return fItem;
          })
        }
        this.vehicleIniApplyData=JSON.parse(JSON.stringify(res.data))

        //过滤出技师或者专家的图片
        this.jsImageArr=[]
        this.zjImageArr=[]
        this.vehicleIniApplyData.imgs.forEach((fItem,fIndex)=>{
          if(fItem.type==1){
            this.jsImageArr.push(fItem)
          }else{
            this.zjImageArr.push(fItem)
          }
        })
        //审批状态回显
        this.packingValue=this.columnsMap[this.vehicleIniApplyData.audit]
        //默认选中索引
        this.defaultChooseIndex=this.columns.findIndex(item => item.value ===this.vehicleIniApplyData.audit )
        //状态是否审核通过
        if(this.vehicleIniApplyData.audit==0){
          this.isSHApprove=false
        }else{
          this.isSHApprove=true
        }

        console.log("this.isSHApprove", this.isSHApprove);
      })
    },
    //提交审批
    async auditVehicleIniApplySub() {
      let vehicleIniApply={}
      vehicleIniApply.id=this.vehicleIniApplyData.id
      vehicleIniApply.approverUserName=this.vehicleIniApplyData.applicantRealName
      vehicleIniApply.audit=this.vehicleIniApplyData.audit
      vehicleIniApply.deadline=this.vehicleIniApplyData.deadline
      vehicleIniApply.rewriteTimes=this.vehicleIniApplyData.rewriteTimes||1
      vehicleIniApply.refuseReason=this.vehicleIniApplyData.refuseReason
      //items
      let items=this.vehicleIniApplyData.items.map(mItem=>{
        let Obj={}
        Obj.id=mItem.id
        Obj.writeValue=mItem.writeValue
        Obj.audit=this.vehicleIniApplyData.audit
        return Obj;
      })
      await this.validSubData();
      const data = {
        vehicleIniApply:JSON.stringify(vehicleIniApply),
        items:JSON.stringify(items),
        imgs:JSON.stringify(this.imageFileList)
      }
      // console.log("提交的数据data", data);
      this.$axiosReq({
        url: 'vehicleIniApply/auditVehicleIniApply',
        data,method: 'post', bfLoading: true,
      }).then(res => {
        this.vantToastMixin("数据保存成功")
        this.sleepMixin(500).then(()=>{
          this.routerBackMixin()
        })
      })
    },
  }
}
</script>

<style lang="scss" scoped>
  #WritingApplicationDetail {
    background-color: #F0EFF4;
    padding: 0 12px;
  }
  /*顶部*/
  .WritingApplicationDetail-top{
    .top-item{
      padding: 13px 0;
      border-bottom: 1px solid #ddd;
      width: 100%;
      h4{
        width: 140px;
      }
    }
  }
  /*图片显示*/
  .image-container{
    .tp-container{
      width: 80px;
      height: 80px;
    }
  }

  /*输入item的颜色*/
  .inputItem{
    min-height: 45px;
    border-bottom: 1px solid #ddd;
  }

  .item-choose-item-container{
    position: relative;
    .item-choose-icon{
        position: absolute;
      right: 20px;
      bottom: 10px;
    }
  }


</style>

